"""
客片相关API路由
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import List
from app.database import get_db
from app import models, schemas

router = APIRouter()


@router.get("/gallery", response_model=List[schemas.GalleryItemResponse])
async def get_gallery(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(20, ge=1, le=100, description="返回记录数"),
    db: Session = Depends(get_db)
):
    """
    获取客片列表（用于客片页面）
    
    返回所有启用的作品的第一张图片作为客片展示
    
    - **skip**: 分页偏移量
    - **limit**: 每页数量
    """
    # 查询所有启用的作品，并获取每个作品的第一张图片
    works = db.query(models.Work).filter(
        models.Work.is_active == True
    ).order_by(models.Work.created_at.desc()).offset(skip).limit(limit).all()
    
    gallery_items = []
    for work in works:
        # 获取作品的第一张图片（按sort_order排序）
        first_image = db.query(models.WorkImage).filter(
            models.WorkImage.work_id == work.id
        ).order_by(models.WorkImage.sort_order.asc()).first()
        
        if first_image:
            gallery_items.append({
                "id": first_image.id,
                "image_url": first_image.image_url,
                "title": work.subtitle,  # 使用中文副标题
                "subtitle": work.title,  # 使用英文标题
                "work_id": work.id
            })
    
    return gallery_items

